import React, { useState, useEffect } from 'react';
import {
  Table,
  Button,
  Modal,
  Form,
  Input,
  Select,
  InputNumber,
  Upload,
  message,
  Popconfirm,
  Tag,
  Image,
  Space,
  Card,
  Spin
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  UploadOutlined,
  EyeOutlined,
  RobotOutlined
} from '@ant-design/icons';
import { adminApi } from '../../services/api';

const { Option } = Select;
const { TextArea } = Input;

const DishManagement = () => {
  const [dishes, setDishes] = useState([]);
  const [categories, setCategories] = useState([]);
  const [tags, setTags] = useState([]);
  const [loading, setLoading] = useState(false);
  const [modalVisible, setModalVisible] = useState(false);
  const [editingDish, setEditingDish] = useState(null);
  const [form] = Form.useForm();
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  });
  const [aiGenerating, setAiGenerating] = useState(false);

  useEffect(() => {
    loadDishes();
    loadCategories();
    loadTags();
  }, []);

  const loadDishes = async (page = 1, size = 10) => {
    setLoading(true);
    try {
      const response = await adminApi.dishes.list({ page, size });
      setDishes(response.data?.records || []);
      setPagination({
        current: page,
        pageSize: size,
        total: response.data?.total || 0,
      });
    } catch (error) {
      console.error('加载菜品失败:', error);
    } finally {
      setLoading(false);
    }
  };

  const loadCategories = async () => {
    try {
      const response = await adminApi.categories.all();
      setCategories(response.data || []);
    } catch (error) {
      console.error('加载分类失败:', error);
    }
  };

  const loadTags = async () => {
    try {
      const response = await adminApi.tags.all();
      setTags(response.data || []);
    } catch (error) {
      console.error('加载标签失败:', error);
    }
  };

  const handleTableChange = (pagination) => {
    loadDishes(pagination.current, pagination.pageSize);
  };

  const showModal = (dish = null) => {
    setEditingDish(dish);
    setModalVisible(true);
    if (dish) {
      let detailImages = [];
      if (dish.detailImages) {
        try {
          detailImages = JSON.parse(dish.detailImages);
        } catch (error) {
          console.warn('解析详情图片JSON失败:', error);
          detailImages = [];
        }
      }
      form.setFieldsValue({
        ...dish,
        detailImages,
      });
    } else {
      form.resetFields();
    }
  };

  const handleSubmit = async (values) => {
    try {
      const submitData = {
        ...values,
        detailImages: JSON.stringify(values.detailImages || []),
      };

      if (editingDish) {
        await adminApi.dishes.update(editingDish.id, submitData);
        message.success('更新菜品成功');
      } else {
        await adminApi.dishes.create(submitData);
        message.success('创建菜品成功');
      }
      
      setModalVisible(false);
      loadDishes(pagination.current, pagination.pageSize);
    } catch (error) {
      console.error('保存菜品失败:', error);
    }
  };

  const handleDelete = async (id) => {
    try {
      await adminApi.dishes.delete(id);
      message.success('删除菜品成功');
      loadDishes(pagination.current, pagination.pageSize);
    } catch (error) {
      console.error('删除菜品失败:', error);
    }
  };

  const getCategoryName = (categoryId) => {
    const category = categories.find(c => c.id === categoryId);
    return category ? category.name : '';
  };

  const getTagName = (tagId) => {
    const tag = tags.find(t => t.id === tagId);
    return tag ? tag.name : '';
  };

  const getTagColor = (tagId) => {
    const tag = tags.find(t => t.id === tagId);
    return tag ? tag.color : 'default';
  };

  const handleAiGenerate = async () => {
    const dishName = form.getFieldValue('name');
    if (!dishName) {
      message.warning('请先输入菜品名称');
      return;
    }

    setAiGenerating(true);
    try {
      // 生成AI图片任务
      const generateResponse = await adminApi.aiImage.generate({ dishName });
      if (generateResponse.code !== 200) {
        message.error('生成AI图片任务失败');
        return;
      }

      const taskId = generateResponse.data.taskId;
      message.info('AI图片生成中，请稍候...');

      // 轮询查询任务状态，最多10秒
      const startTime = Date.now();
      const maxWaitTime = 10000; // 10秒
      const pollInterval = 1000; // 1秒

      const pollTaskStatus = async () => {
        try {
            const resultResponse = await adminApi.aiImage.getResult(taskId);
             if (resultResponse.code === 200 && resultResponse?.data?.imageUrl) {
                form.setFieldsValue({ mainImage: resultResponse.data.imageUrl });
                message.success('AI图片生成成功！');
                return;
              }

          // 检查是否超时
          if (Date.now() - startTime < maxWaitTime) {
            setTimeout(pollTaskStatus, pollInterval);
          } else {
            message.error('AI图片生成超时，请稍后重试');
          }
        } catch (error) {
          console.error('查询任务状态失败:', error);
          message.error('查询任务状态失败');
        }
      };

      // 开始轮询
      setTimeout(pollTaskStatus, pollInterval);
    } catch (error) {
      console.error('AI图片生成失败:', error);
      message.error('AI图片生成失败');
    } finally {
      setAiGenerating(false);
    }
  };

  const handleListAiGenerate = async (dish) => {
    setAiGenerating(true);
    try {
      // 生成AI图片任务
      const generateResponse = await adminApi.aiImage.generate({ dishName: dish.name });
      if (generateResponse.code !== 200) {
        message.error('生成AI图片任务失败');
        return;
      }

      const taskId = generateResponse.data.taskId;
      message.info('AI图片生成中，请稍候...');

      // 轮询查询任务状态，最多10秒
      const startTime = Date.now();
      const maxWaitTime = 10000; // 10秒
      const pollInterval = 1000; // 1秒

      const pollTaskStatus = async () => {
        try {
          const resultResponse = await adminApi.aiImage.getResult(taskId);
          if (resultResponse.code === 200 && resultResponse?.data?.imageUrl) {
            // 更新菜品数据
            await adminApi.dishes.update(dish.id, {
              ...dish,
              mainImage: resultResponse.data.imageUrl
            });
            message.success('AI封面生成并更新成功！');
            loadDishes(pagination.current, pagination.pageSize);
            return;
          }

          // 检查是否超时
          if (Date.now() - startTime < maxWaitTime) {
            setTimeout(pollTaskStatus, pollInterval);
          } else {
            message.error('AI图片生成超时，请稍后重试');
          }
        } catch (error) {
          console.error('查询任务状态失败:', error);
          message.error('查询任务状态失败');
        }
      };

      // 开始轮询
      setTimeout(pollTaskStatus, pollInterval);
    } catch (error) {
      console.error('AI图片生成失败:', error);
      message.error('AI图片生成失败');
    } finally {
      setAiGenerating(false);
    }
  };

  const columns = [
    {
      title: '主图',
      dataIndex: 'mainImage',
      key: 'mainImage',
      width: 100,
      render: (mainImage) => (
        <Image
          src={mainImage}
          alt="菜品图片"
          width={60}
          height={60}
          style={{ objectFit: 'cover', borderRadius: 4 }}
          fallback=""
        />
      ),
    },
    {
      title: '菜品名称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '分类',
      dataIndex: 'categoryId',
      key: 'categoryId',
      render: (categoryId) => getCategoryName(categoryId),
    },
    {
      title: '卡路里',
      dataIndex: 'calories',
      key: 'calories',
      render: (calories) => `${calories} 卡`,
    },
    {
      title: '标签',
      dataIndex: 'tagIds',
      key: 'tagIds',
      render: (tagIds) => (
        <div>
          {tagIds?.map(tagId => (
            <Tag key={tagId} color={getTagColor(tagId)}>
              {getTagName(tagId)}
            </Tag>
          ))}
        </div>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      render: (time) => new Date(time).toLocaleString(),
    },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => (
        <Space>
          <Button
            type="link"
            icon={<EyeOutlined />}
            onClick={() => showModal(record)}
          >
            查看
          </Button>
          <Button
            type="link"
            icon={<EditOutlined />}
            onClick={() => showModal(record)}
          >
            编辑
          </Button>
          <Button
            type="link"
            icon={<RobotOutlined />}
            loading={aiGenerating}
            onClick={() => handleListAiGenerate(record)}
          >
            AI封面
          </Button>
          <Popconfirm
            title="确定要删除这道菜品吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button type="link" danger icon={<DeleteOutlined />}>
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card>
        <div style={{ marginBottom: 16 }}>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            onClick={() => showModal()}
          >
            新增菜品
          </Button>
        </div>

        <Table
          columns={columns}
          dataSource={dishes}
          rowKey="id"
          loading={loading}
          pagination={{
            ...pagination,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
          }}
          onChange={handleTableChange}
        />
      </Card>

      <Modal
        title={editingDish ? '编辑菜品' : '新增菜品'}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        footer={null}
        width={800}
      >
        <Form
          form={form}
          layout="vertical"
          onFinish={handleSubmit}
        >
          <Form.Item
            name="name"
            label="菜品名称"
            rules={[{ required: true, message: '请输入菜品名称' }]}
          >
            <Input placeholder="请输入菜品名称" />
          </Form.Item>

          <Form.Item
            name="categoryId"
            label="分类"
            rules={[{ required: true, message: '请选择分类' }]}
          >
            <Select placeholder="请选择分类">
              {categories.map(category => (
                <Option key={category.id} value={category.id}>
                  {category.name}
                </Option>
              ))}
            </Select>
          </Form.Item>

          <Form.Item
            name="calories"
            label="卡路里"
            rules={[{ required: true, message: '请输入卡路里' }]}
          >
            <InputNumber
              placeholder="请输入卡路里"
              min={0}
              style={{ width: '100%' }}
              addonAfter="卡"
            />
          </Form.Item>

          <Form.Item
            name="mainImage"
            label={
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                <span>主图URL</span>
                <Button
                  type="primary"
                  size="small"
                  icon={<RobotOutlined />}
                  loading={aiGenerating}
                  onClick={handleAiGenerate}
                  style={{ marginLeft: 8 }}
                >
                  AI生成
                </Button>
              </div>
            }
            rules={[{ required: true, message: '请输入主图URL' }]}
          >
            <Input placeholder="请输入主图URL" />
          </Form.Item>

          <Form.Item
            name="detailImages"
            label="详情图片URLs（每行一个）"
          >
            <TextArea
              placeholder="请输入详情图片URLs，每行一个"
              rows={4}
              onChange={(e) => {
                const urls = e.target.value.split('\n').filter(url => url.trim());
                form.setFieldsValue({ detailImages: urls });
              }}
            />
          </Form.Item>

          <Form.Item
            name="description"
            label="描述"
          >
            <TextArea
              placeholder="请输入菜品描述"
              rows={3}
            />
          </Form.Item>

          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit">
                {editingDish ? '更新' : '创建'}
              </Button>
              <Button onClick={() => setModalVisible(false)}>
                取消
              </Button>
            </Space>
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default DishManagement;